<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Table, TableColumn } from '@/components/Table'
import { Dialog } from '@/components/Dialog'
import { Form, FormSchema } from '@/components/Form'
import { ElMessageBox, ElMessage } from 'element-plus'
import { BaseButton } from '@/components/Button'
import { Icon } from '@/components/Icon'

import { ref, reactive, computed, unref } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import {
  getButtonListApi,
  updateButtonApi,
  deleteButtonApi
} from '@/api/systemSettings/buttonManage'
import { pick } from 'lodash-es'

// Table
const columns: TableColumn[] = [
  {
    field: 'id',
    label: '序号',
    showOverflowTooltip: false,
    width: '80'
  },
  {
    field: 'name',
    label: '名称'
  },
  {
    field: 'code',
    label: '编码'
  },
  {
    field: 'status',
    label: '状态',
    slots: {
      default: ({ row }) =>
        row.status === 1 ? (
          <div class="color-[#16a34a]">启用</div>
        ) : (
          <div class="color-[#dc2626]">禁用</div>
        )
    }
  },
  {
    field: 'action',
    label: '操作',
    width: 170,
    slots: {
      default: ({ row }) => (
        <div class="flex items-center gap-x-[10px]">
          <BaseButton type="primary" size="small" onClick={() => onOpenDialog(row)}>
            {{
              icon: () => <Icon size={20} icon="carbon:edit" />,
              default: () => '编辑'
            }}
          </BaseButton>
          <BaseButton class="!ml-0" type="danger" size="small" onClick={() => onDelete(row)}>
            {{
              icon: () => <Icon size={20} icon="material-symbols:delete-outline" />,
              default: () => '删除'
            }}
          </BaseButton>
        </div>
      )
    }
  }
]

const { tableMethods, tableState } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const { data, count } = await getButtonListApi({
      pageNo: unref(currentPage),
      pageSize: unref(pageSize)
    })
    return {
      list: data,
      total: count
    }
  }
})
const { loading, dataList, total, pageSize, currentPage } = tableState
const { refresh } = tableMethods

// Dialog
const visible = ref(false)
const isEdit = ref(false)
const title = computed(() => (isEdit.value ? '编辑按钮' : '新增按钮'))

// Form
const { formRegister, formMethods } = useForm()
const { getElFormExpose, setValues, getFormData } = formMethods

const { required } = useValidator()

const schema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: '名称',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'code',
    label: '编码',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'status',
    label: '状态',
    value: 0,
    component: 'RadioGroup',
    componentProps: {
      options: [
        { label: '启用', value: 1 },
        { label: '禁用', value: 0 }
      ]
    }
  }
])

// 打开弹窗
const onOpenDialog = (row?) => {
  visible.value = true
  isEdit.value = !!row
  if (row) {
    // 编辑
    setValues(pick(row, ['id', 'name', 'code', 'status']))
  }
}

//删除
const onDelete = (row) => {
  ElMessageBox.confirm('是否删除该按钮?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await deleteButtonApi({ ids: row.id })
      ElMessage.success('操作成功！')
      refresh()
    })
    .catch(() => {})
}

// 重置
const onReset = async () => {
  const elFormExpose = await getElFormExpose()
  elFormExpose?.resetFields()
}

const disabled = ref(false)
// 立即提交
const onFormSubmit = async () => {
  disabled.value = true
  const formData = await getFormData()
  updateButtonApi(formData)
    .then(() => {
      visible.value = false
      ElMessage.success('操作成功！')
      refresh()
    })
    .catch((err) => {
      console.log(err)
    })
    .finally(() => {
      disabled.value = false
    })
}
</script>

<template>
  <ContentWrap title="按钮管理">
    <template #action>
      <BaseButton type="primary" @click="onOpenDialog">
        <template #icon>
          <Icon :size="20" icon="material-symbols:add" />
        </template>
        新增
      </BaseButton>
    </template>
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="columns"
      :data="dataList"
      :pagination="{ total: total }"
      :loading="loading"
      @refresh="refresh"
    />

    <!-- 新增按钮/编辑-弹窗 -->
    <Dialog
      v-model="visible"
      :title="title"
      width="500"
      maxHeight="500"
      :close-on-click-modal="false"
    >
      <Form
        class="w-[400px] ml-[auto] mr-[auto]"
        :schema="schema"
        :isCol="false"
        @register="formRegister"
      />
      <template #footer>
        <div class="text-center mb-[16px]">
          <BaseButton v-if="!isEdit" @click="onReset">重置</BaseButton>
          <BaseButton type="primary" :disabled="disabled" debounce @click="onFormSubmit"
            >立即提交</BaseButton
          >
        </div>
      </template>
    </Dialog>
  </ContentWrap>
</template>
